import Vue from 'vue';

const ToastConstructor = Vue.extend(require('./toast.vue'));

let toastPool = [];

// 释放一个实例
let getAnInstance = () => {

	if(toastPool.length > 0) {

		let instance = toastPool[0];

		toastPool.splice(0, 1);
		return instance;

	}

	return new ToastConstructor({
		el: document.createElement('div')
	});

};

// 保存一个实例
let returnAnInstance = instance => {
	if(instance) {
		toastPool.push(instance);
	}
};

// 动画结束移除节点
let removeDom = event => {
	if(event.target.parentNode) {
		event.target.parentNode.removeChild(event.target);
	}
};

// 定义弹窗关闭函数
ToastConstructor.prototype.close = function() {

	this.visible = false;
	this.$el.addEventListener('transitionend', removeDom);
	this.closed = true;
	
	// 动画结束移除保存的数组实例
	returnAnInstance(this);

};

// 定义一个方法，生成Vue 实例，并且配置相应信息
let Toast = (options = {}) => {

	let duration = options.duration || 3000; // 显示时长

	let instance = getAnInstance(); // 拿到 Vue 实例，然后挂载

	instance.closed = false; // 定义一个是否关闭的标识符

	clearTimeout(instance.timer);

	// 默认样式
	instance.message = typeof options === 'string' ? options : options.message;
	instance.position = options.position || 'middle';
	instance.className = options.className || '';
	instance.iconClass = options.iconClass || '';

	document.body.appendChild(instance.$el); // 挂载 Vue 实例
	
	// 挂载成功 ，开始 显示
	Vue.nextTick(function() {

		instance.visible = true; // 是否显示标识符

		instance.$el.removeEventListener('transitionend', removeDom);

		~duration && (instance.timer = setTimeout(function() {

			if(instance.closed) return;

			instance.close();

		}, duration));

	});

	return instance;
};

export default Toast;